import React, { useEffect, useRef, useState } from "react"
import NavTop from "../../components/NavTop"
import { Button, Form, Input, Toast } from "antd-mobile"
import "./index.scss"
import { useDispatch } from "react-redux"
import { getCode, login } from "../../store/actions"
import { useHistory, useLocation } from "react-router-dom"
function Login() {
  const location = useLocation()
  const history = useHistory()
  const dispatch = useDispatch()
  const [form] = Form.useForm()
  // 发送验证码
  const mobileRef = useRef(null)
  // 倒计时状态
  const [timeLeft, setTimeLeft] = useState(0)
  // 定时器 ref
  const timerRef = useRef(-1)
  const handleCode = () => {
    const mobile = form.getFieldValue("mobile") ?? ""
    const hasError = form.getFieldError("mobile").length > 0
    if (mobile.trim() === "" || hasError) {
      return mobileRef.current?.focus()
    }
    // 获取验证码
    dispatch(getCode(mobile))
    // 设置倒计时时间
    setTimeLeft(60)
    // 开启计时器
    timerRef.current = window.setInterval(() => {
      setTimeLeft((timeLeft) => timeLeft - 1)
    }, 1000)

    Toast.show({
      content: "验证码已发送",
      duration: 600
    })
  }
  // 登录
  const onFinish = async (values) => {
    await dispatch(login(values))
    try {
      // 登录成功后的操作
      Toast.show({
        content: "登录成功",
        duration: 800,
        afterClose: () => {
          history.replace(location.state?.from ?? "/home/my")
        }
      })
    } catch (error) {
      Toast.show({
        content: "登录失败",
        duration: 1000
      })
    }
  }
  useEffect(() => {
    if (timeLeft === 0) {
      // 清理定时器
      window.clearInterval(timerRef.current)
    }
  }, [timeLeft])
  return (
    <div>
      <NavTop></NavTop>
      <div className="wrapper">
        <h3>短信登录</h3>
        <Form layout="horizontal" mode="card" form={form} onFinish={onFinish}>
          <Form.Item
            name="mobile"
            validateTrigger="onBlur"
            rules={[
              {
                required: true,
                message: "请输入手机号"
              },
              {
                message: "手机号格式错误",
                pattern: /^1[3-9]\d{9}$/
              }
            ]}
          >
            <Input ref={mobileRef} placeholder="请输入手机号" />
          </Form.Item>
          <Form.Item
            name="code"
            validateTrigger="onBlur"
            rules={[
              { required: true, message: "请输入验证码" },
              {
                pattern: /^\d{6}$/,
                message: "验证码为6个数字"
              }
            ]}
            extra={
              <span onClick={timeLeft === 0 ? handleCode : undefined}>
                {timeLeft === 0 ? "发送验证码" : `${timeLeft}秒后获取`}
              </span>
            }
          >
            <Input placeholder="请输入验证码" />
          </Form.Item>
          <Form.Item>
            <Button type="submit">登录</Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  )
}

export default Login
